package com.linkgie.galaxyframework.crypto.context;

import com.linkgie.galaxyframework.crypto.Algorithm;
import com.linkgie.galaxyframework.crypto.Cryptogram;
import com.linkgie.galaxyframework.crypto.spi.Cryptobytes;
import com.linkgie.galaxyframework.crypto.spi.CryptobytesCodec;

public class AbstractCryptogramCodec<T extends Cryptogram, B extends Cryptobytes> implements CryptogramCodec<T>{
	
	private Algorithm ALGORITHM;
	
	private Encoding encoding;

	private CryptobytesCodec<B> bytesCodec;
	
	private CryptogramConstuctor<T> contructor;
	
	@Override
	public boolean isSupported(byte[] cryptogramBytes, int offset, int length) {
		byte[] baseCryptobytes = encoding.decodedContent(cryptogramBytes, offset, length);
		return bytesCodec.isSupported(baseCryptobytes);
	}

	@Override
	public T decode(byte[] cryptogramBytes, int offset, int length) {
		B cbytes = bytesCodec.decode(cryptogramBytes, offset, length);
		if (cbytes == null) {
			return null;
		}
		
		return contructor.create(ALGORITHM, cbytes);
	}

	@Override
	public T encode(byte[] rawBytes) {
		B cbytes = bytesCodec.encode(rawBytes);
		
		return contructor.create(ALGORITHM, cbytes);
	}


}
